//index.js
const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: '',
    userInfo: {
      'avatarUrl': '../../images/header.png',
      'name': "",
      'jobNum': "",
      exercisePersonTrips:'',
      officialPersonTrips:""
    },
    challengeState:false,
    popupState:false,
    hasUserInfo: false,
    challenge:[],
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  qualifying(e) {
    wx.showLoading({
      title: '加载试卷...',
      mask: true,
    })

    app.globalData.answerType = e.currentTarget.dataset.type
    this.obtainPapers(e.currentTarget.dataset.type).then((value) => {
      if (value.length <= 0) {
        wx.showToast({
          title: '没有可用试卷！',
          image: "../../images/error.png",
          icon: 'none',
          duration: 2000
        })
      } else {
        app.globalData.formalPapers = value
        wx.navigateTo({
          url: `/pages/qualifierList/qualifierList`
        })
      }
    }).catch((e) => {
      wx.hideLoading();
    })
  },

  routerOffcial(e) {
    wx.showLoading({
      title: '加载试卷...',
      mask: true,
    })
    
    app.globalData.answerType = e.currentTarget.dataset.type
    this.obtainPapers(e.currentTarget.dataset.type).then((value)=>{
      if (value.length <= 0) {
        wx.showToast({
          title: '没有可用试卷！',
          image: "../../images/error.png",
          icon: 'none',
          duration: 2000
        })
      } else {
        app.globalData.formalPapers = value
        wx.navigateTo({
          url: `/pages/qualifier/qualifier`
        })
      }
    }).catch((e)=>{
      wx.hideLoading();
    })
    
  },

  setRouter() {
    let userInfo = this.data.userInfo
    wx.navigateTo({
        url: `/pages/set/set?jobNum=${userInfo.jobNum}&avatarUrl=${userInfo.avatarUrl}&name=${userInfo.name}`
    })
  },

  obtainPapers(type) {
    return new Promise((resolve, reject)=>{
      qcloud.request({
        url: config.service.obtainPapers,
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        login: true,
        data: {
          'type': type || 0
        },
        success: (response) => {
          var data = response.data
          if (data.code === 0) {
            resolve(data.paperDTOs)
          } else {
            reject(data.message)
          }
        },
        fail: function (err) {
          console.log(err);
        },
        complete: function () {
          wx.hideLoading();
        },

      })
    })
    
  },

  routerFn(e){
    app.globalData.answerType = e.currentTarget.dataset.type
    wx.showLoading({
      title: '加载试卷...',
      mask: true,
    })

    this.obtainPapers(e.currentTarget.dataset.type).then((value)=>{

      if (value.length <= 0) {
        wx.showToast({
          title: '没有可用试卷！',
          image: "../../images/error.png",
          icon: 'none',
          duration: 2000
        })
      } else {
        app.globalData.formalPapers = value
        wx.navigateTo({
          url: `/pages/qualifier/qualifier`
        })
      }
    }).catch((e) => {
      wx.hideLoading();
    })
  },

  onGotUserInfo: function (e) {
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        popupState: false
      })
      this.getObtainSelfInfo()
    }
  },

  onLoad: function () {
    var that = this;
    //读取用户信息缓存
    wx.getStorage({
      key: 'userInfo',
      success: function(res) {
        if (res.data != "") {
          that.setData({
            userInfo: res.data
          })
          app.globalData.uId = res.data.uId

          that.obtainPaperNotices(app.globalData.uId)
        }
      },
    })

    //读取答题次数信息
    wx.getStorage({
      key: 'exercisePersonTrips',
      success: function (res) {
        if (res.data != "") {
          that.setData({
            exercisePersonTrips: res.data
          })
        }
      },
    })
    wx.getStorage({
      key: 'officialPersonTrips',
      success: function (res) {
        if (res.data != "") {
          that.setData({
            officialPersonTrips: res.data
          })
        }
      },
    })
    wx.getStorage({
      key: 'qualifyingPersonTrips',
      success: function (res) {
        if (res.data != "") {
          that.setData({
            qualifyingPersonTrips: res.data
          })
        }
      },
    })
    // wx.getUserInfo({
    //     success :(userResult) =>{
    //       this.getObtainSelfInfo()
    //     },

    //     fail: (e) => {
    //       that.setData({
    //         popupState: true
    //       })
    //     }

    // });
    
  },

  onShow: function() {
    var that = this;

    wx.getUserInfo({
      success: (userResult) => {
        this.getObtainSelfInfo()
      },

      fail: (e) => {
        that.setData({
          popupState: true
        })
      }

    });
  },

  getObtainSelfInfo() {
    qcloud.request({
      url: config.service.obtainSelfInfo,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      login: true,
      data: {},
      success: (response) => {
        var data = response.data
        if (data.code === 202) {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        } else if (data.code === 0) {
          this.setData({
            userInfo: data.userDTO
          })

          app.globalData.uId = data.userDTO.uId

          wx.setStorage({
            key: 'userInfo',
            data: data.userDTO,
          })

          this.obtainPapersPersonTrips()
        } else {
          wx.showToast({
            title: '网络错误！',
            image: "../../images/error.png",
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: (err) => {
      }
    });


  },

  obtainPapersPersonTrips(){
    qcloud.request({
      url: config.service.obtainPapersPersonTrips,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      login: true,
      success: (response) => {
        var data = response.data
        if (data.code === 0) {
          this.setData({
            exercisePersonTrips: data.exercisePersonTrips
          })

          this.setData({
            officialPersonTrips: data.officialPersonTrips
          })

          this.setData({
            qualifyingPersonTrips: data.qualifyingPersonTrips
          })

          wx.setStorage({
            key: 'exercisePersonTrips',
            data: data.exercisePersonTrips,
          })

          wx.setStorage({
            key: 'officialPersonTrips',
            data: data.officialPersonTrips,
          })

          wx.setStorage({
            key: 'qualifyingPersonTrips',
            data: data.qualifyingPersonTrips,
          })
        } else {

        }
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },

  obtainPaperNotices(uId) {
    qcloud.request({
      url: config.service.obtainPaperNotices,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { 'uId': uId},
      login: true,
      success: (response) => {
        let data = response.data
        if(data.code === 0) {

          let paperNoticeDTOs = data.paperNoticeDTOs.splice(0, 3)

          paperNoticeDTOs.forEach((value, index) => {
            if (!!value.isOpen) {
              this.setData({
                challenge: this.data.challenge.concat(value)
              })
            } else {
              let pattern = "yyyy年MM月dd hh时mm分ss"
              let nearestDuration = value.nearestDuration
              if (!nearestDuration) return;
              let weekIarr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
              value.startTime = `${weekIarr[nearestDuration.weekDay - 1]} ${nearestDuration.startTime}`

              this.setData({
                challenge: this.data.challenge.concat(value)
              })
            }
          })

          let idata = new Date().getDate()

          if ( wx.getStorageSync('idata') != '' ) {
            let state = wx.getStorageSync('idata') < idata || (idata == '1' && wx.getStorageSync('idata') != '1') 
              
            this.setData({
              challengeState: this.data.challenge.length > 0 && state
            })

            if( wx.getStorageSync('idata') < idata ) {
              wx.setStorage({
                key:'idata',
                data: idata
              })
            }
          } else {
            wx.setStorage({
              key:'idata',
              data: idata
            })
            this.setData({
              challengeState: this.data.challenge.length > 0
            })
          }
          
        }
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },

  deleteFn() {
    this.setData({
      challengeState:false
    })
  },

  setRouter(e) {
    if (e.currentTarget.dataset.open == true) {
      let id = e.currentTarget.dataset.id
      let icon = e.currentTarget.dataset.icon
      app.globalData.answerType = e.currentTarget.dataset.type

      wx.navigateTo({
        url: `/pages/officialExplain/officialExplain?id=${id}&icon=${icon}`
      })
    }
  }
})
